package com.yzt.insys.exception;

import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.yzt.insys.util.DateUtil;
import com.yzt.insys.util.MyMailSender;

public class MappingException extends SimpleMappingExceptionResolver {

	private MyMailSender mailSender;
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String str="<html><head></head><body>";
		str+="时间:"+DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss")+"<br>";
		StackTraceElement [] messages=ex.getStackTrace();
		StackTraceElement element=null;
		str+=ex.getClass().getName()+"<br />";
		for(int i=0,length=messages.length;i<length;i++){
			element=messages[i];
			str+="at "+element.getClassName()+"."
			+element.getMethodName()
			+"("+element.getFileName()
			+":"+element.getLineNumber()+")";
		    str+="<br />";
		}
		str+="</body></html>";
		logger.error(str);
		sendWidthHtml(str);
		return super.doResolveException(request, response, handler, ex);
	}
	
	private void sendWidthHtml(String str) {
		MimeMessage mailMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper;
		try {
			messageHelper = new MimeMessageHelper(mailMessage,true);
			messageHelper.setTo(mailSender.getReceivers());
			messageHelper.setFrom(mailSender.getUsername());
			messageHelper.setSubject("异常邮件:"+DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
			messageHelper.setText(str, true);
			mailSender.send(mailMessage);
		} catch (MessagingException e) {
			e.printStackTrace();
			logger.error(DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss")+"邮件发送失败");
		}
	}

	public MyMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(MyMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	
	
}
